/*
 * UnitAnimalPosition.cpp
 *
 *  Created on: 2013-1-19
 *      Author: heqiu
 */

#include "UnitAnimalPosition.h"
namespace guud {

UnitAnimalPosition::UnitAnimalPosition() {
	m_uiLong = 0;
}

void UnitAnimalPosition::init(uint32_t uiLong) {
	m_uiLong = uiLong;
}

void UnitAnimalPosition::getAnimal(uint32_t uiX, uint32_t uiY,
		std::vector<uint32_t> & vctAnimal) {
	uint32_t uiPos = uiX * (m_uiLong + 1) + uiY;
	m_lock.lock();
	std::map<uint32_t, std::set<uint32_t> >::iterator it = m_mapPos.find(uiPos);
	if (it != m_mapPos.end()) {
		std::set<uint32_t> & tmpSet = it->second;
		std::set<uint32_t>::iterator itSet;
		for (itSet = tmpSet.begin(); itSet != tmpSet.end(); itSet++) {
			vctAnimal.push_back(*itSet);
		}
	}
	m_lock.unlock();
}
void UnitAnimalPosition::delAnimal(uint32_t uiId) {
	m_lock.lock();
	std::map<uint32_t, uint32_t>::iterator it = m_mapAnimal.find(uiId);
	if (it != m_mapAnimal.end()) {
		m_mapPos[it->second].erase(it->first);
		m_mapAnimal.erase(it);
	}
	m_lock.unlock();
}
void UnitAnimalPosition::addAnimal(uint32_t uiId, uint32_t uiX, uint32_t uiY) {
	uint32_t uiPos = uiX * (m_uiLong + 1) + uiY;
	m_lock.lock();
	std::map<uint32_t, uint32_t>::iterator it = m_mapAnimal.find(uiId);
	if (it == m_mapAnimal.end()) {
		m_mapAnimal[uiId] = uiPos;
		m_mapPos[uiPos].insert(uiId);
	} else {
		if (it->second != uiPos) {
			m_mapPos[it->second].erase(uiId);
			it->second = uiPos;
			m_mapPos[uiPos].insert(uiId);
		}
	}
	m_lock.unlock();
}
}
